from flask import Blueprint, render_template, request
from flask_login import current_user

from applications.common import curd
from applications.common.curd import model_to_dicts, enable_status, disable_status
from applications.common.helper import ModelFilter
from applications.common.helper import Tools
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Equipment
from applications.schemas import EquipmentOutSchema

admin_device = Blueprint('admin_device', __name__, url_prefix='/admin/device')


@admin_device.route('/')
@authorize("admin:device:main")
def main():
    return render_template('admin/device/main.html')


#   用户分页查询
@admin_device.get('/data')
@authorize("admin:device:main")
def data():
    # 获取请求参数
    name = str_escape(request.args.get("name"))
    # 查询参数构造
    mf = ModelFilter()
    if name:
        mf.contains(field_name="name", value=name)
    # orm查询
    # 使用分页获取data需要.items
    device = Equipment.query.filter(mf.get_filter(Equipment)).layui_paginate()
    count = device.total
    # 返回api
    return table_api(data=model_to_dicts(schema=EquipmentOutSchema, data=device.items), count=count)


# 用户增加
@admin_device.get('/add')
@authorize("admin:device:add", log=True)
def add():
    return render_template('admin/device/add.html')


@admin_device.post('/save')
@authorize("admin:device:add", log=True)
def save():
    req_json = request.json
    name = str_escape(req_json.get("name"))
    notes = str_escape(req_json.get('notes'))
    user_id = current_user.id
    if not notes:
        notes = ''
    if not name:
        return fail_api(msg="设备名称不能为空")
    if bool(Equipment.query.filter_by(name=name).count()):
        return fail_api(msg="设备已经存在")
    device_no = 'DE' + Tools.random_string_generator(str_size=8)
    equipment = Equipment(name=name, notes=notes, user_id=user_id, device_no=device_no)

    db.session.add(equipment)
    db.session.commit()
    return success_api(msg="增加成功")


# 删除用户
@admin_device.delete('/remove/<int:id>')
@authorize("admin:device:remove", log=True)
def delete(id):
    res = Equipment.query.filter_by(id=id).delete()
    if not res:
        db.session.rollback()
        return fail_api(msg="删除失败")
    db.session.commit()
    return success_api(msg="删除成功")


#  编辑
@admin_device.get('/edit/<int:id>')
@authorize("admin:device:edit", log=True)
def edit(id):
    equipment = curd.get_one_by_id(Equipment, id)
    return render_template('admin/device/edit.html', info=equipment)


#  更新
@admin_device.put('/update')
@authorize("admin:device:edit", log=True)
def update():
    json = request.json
    info_id = json.get("id"),
    up_data = {
        "name": str_escape(json.get("name")),
        "notes": str_escape(json.get("notes"))
    }
    d = Equipment.query.filter_by(id=info_id).update(up_data)
    if not d:
        db.session.rollback()
        return fail_api(msg="更新失败")
    db.session.commit()
    return success_api(msg="更新成功")


# 启用
@admin_device.put('/enable')
@authorize("admin:device:edit", log=True)
def enable():
    _id = request.json.get('id')
    if _id:
        res = enable_status(model=Equipment, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用
@admin_device.put('/disable')
@authorize("admin:device:edit", log=True)
def dis_enable():
    _id = request.json.get('id')
    if _id:
        res = disable_status(model=Equipment, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")
31.96
32
31.95
32.14
31.66
31.98
31.86
31.96
31.96
31.93
23.78